// pages/cart/cart.js
import {
  findCartList,
  changeChecked,
  addToCart,
  delShop,
} from "../../api/cart";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartList: [], //购物车数据列表
    isAllChecked:true//是否全选/全不选
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCartList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let token = wx.getStorageSync("flower-token");
    if (token) {
      this.getCartList();
    } else {
      // 引导用户去登陆页面
      wx.navigateTo({
        url: "/pages/login/login",
      });
    }
  },
  // 获取购物车列表数据的功能函数
  async getCartList() {
    try {
      const result = await findCartList();
      if (result.code === 200) {
        this.setData({
          cartList: result.data,
        });
      }
    } catch (error) {
      console.log(error);
    }
  },
  //  左侧选项卡的回调
  handleChangeChecked(e) {
    let goodsId = e.currentTarget.dataset.goodid;
    let isChecked = e.detail ? 1 : 0;
    // 调用选中状态功能函数
    this.changeShopChecked(goodsId, isChecked);
  },
  //  修改商品选中状态的功能函数
  async changeShopChecked(goodsId, isChecked) {
    try {
      const result = await changeChecked(goodsId, isChecked);
      if (result.code === 200) {
        // 更新购物车数据列表
        this.getCartList();
      }
    } catch (error) {
      console.log(error);
    }
  },
  // 商品数量回调
  handleChangeCount(e) {
    //  console.log(e);
    let { goodsid, oldcount } = e.currentTarget.dataset;
    let newcount = e.detail;
    let count = newcount - oldcount; //差值
    // 只有新旧差值不为0 才发请求
    count !== 0 && this.addToCartAndChangeCount({ goodsId: goodsid, count });
  },
  // 修改购物车数量的功能函数
  async addToCartAndChangeCount(options) {
    try {
      const result = await addToCart(options);
      if (result.code === 200) {
        this.getCartList();
      }
    } catch (error) {}
  },
  // 点击删除按钮的回调
  handleDelShop(e) {
    wx.showModal({
      title: "你确定删除这个商品吗",
      content: e.currentTarget.dataset.name,
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "确定",
      confirmColor: "#3CC51F",
      success: (result) => {
        if (result.confirm) {
          let goodsId = e.currentTarget.dataset.goodsid;
          this.deleteShop(goodsId);
        }
      },
    });
  },
  // 删除商品的功能函数
  async deleteShop(goodsId) {
    try {
      const result = await delShop(goodsId);
      if (result.code === 200) {
        this.getCartList();
      }
    } catch (error) {}
  },
});
